package socketTransmission;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.*;

public class SocketConnection {

	private Socket connection;
	private ObjectOutputStream out;
	private ObjectInputStream in;
	
	SocketConnection(Socket connection){
		this.connection = connection;
		initialConnection();
	}
	
	private void initialConnection() {
		try {
			
			out = new ObjectOutputStream(connection.getOutputStream());
			out.flush();
			in = new ObjectInputStream(connection.getInputStream());
			
		} catch (UnknownHostException unknownHost) {

		} catch (IOException ioException) {
		}
	}
	
	public void sendMessage(Message msg){
		try {
			out.writeObject(msg);
			out.flush();
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}
	
	public Message receiveMessage(){
		Message msg = null;
		try {
			msg = (Message) in.readObject();
			return msg;
		} catch (ClassNotFoundException classNot) {
			System.err.println("data received in unknow format");
		}catch(IOException ioException){
			
		}
		return msg;
		
	}
	
	public void closeConnection()
	{
		try {
			in.close();
			out.close();
			connection.close();
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}
	
	
}
